<template>
  <div class="dashboard-container horizontal-layout">
    <!-- 自定义标题栏 (仅在Electron环境下显示) -->
    <TitleBar v-if="isElectron" />

    <!-- 顶部导航栏 -->
    <header class="dashboard-header">
      <div class="header-left">
        <div class="logo">
          <el-icon class="logo-icon"><Folder /></el-icon>
          <span class="logo-text">RickPan</span>
        </div>

        <GlobalSearch />
      </div>

      <div class="header-right">
        <!-- 存储空间显示 -->
        <div class="storage-info-horizontal">
          <div class="storage-text">
            <span class="storage-label">{{ t('dashboard.layout.storage.title') }}</span>
            <span class="storage-usage">
              {{ formatFileSize(authStore.user?.storageUsed || 0) }} /
              {{ formatFileSize(authStore.user?.storageQuota || 0) }}
            </span>
          </div>
          <div class="storage-progress">
            <el-progress
              :percentage="storagePercentage"
              :color="storageColor"
              :stroke-width="6"
              :show-text="false"
            />
          </div>
        </div>

        <!-- 主题切换按钮 -->
        <el-tooltip :content="t('dashboard.layout.themeTooltip')" placement="bottom">
          <el-button
            text
            circle
            @click="toggleTheme"
            class="theme-toggle-btn"
          >
            <el-icon>
              <Sunny v-if="themeStore.isDark" />
              <Moon v-else />
            </el-icon>
          </el-button>
        </el-tooltip>

        <el-dropdown @command="handleUserCommand">
          <div class="user-info">
            <el-avatar :size="32" :src="authStore.user?.avatarUrl">
              {{ authStore.user?.username?.charAt(0) || authStore.user?.realName?.charAt(0) }}
            </el-avatar>
            <span class="username">{{ authStore.user?.username || authStore.user?.realName }}</span>
            <el-icon><ArrowDown /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="vip" class="vip-menu-item">
                <el-icon>
                  <Medal />
                </el-icon>
                <span v-if="authStore.user?.userType === 'VIP'">VIP会员</span>
                <span v-else>升级VIP</span>
                <el-tag v-if="authStore.user?.userType === 'VIP'" type="warning" size="small">VIP</el-tag>
              </el-dropdown-item>
              <el-dropdown-item divided command="profile">
                <el-icon><User /></el-icon>
                {{ t('dashboard.layout.userMenu.profile') }}
              </el-dropdown-item>
              <el-dropdown-item command="settings">
                <el-icon><Setting /></el-icon>
                {{ t('dashboard.layout.userMenu.settings') }}
              </el-dropdown-item>
              <el-dropdown-item divided command="logout">
                <el-icon><SwitchButton /></el-icon>
                {{ t('dashboard.layout.userMenu.logout') }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </header>

    <!-- 水平导航栏 -->
    <nav class="horizontal-nav">
      <div class="nav-container">
        <div class="nav-section">
          <!-- <span class="nav-section-title">{{ t('dashboard.layout.sidebar.fileManagement') }}</span> -->
          <div class="nav-items">
            <el-tooltip
              v-for="item in fileMenus"
              :key="item.path"
              :content="t(item.title)"
              placement="bottom"
              :show-after="500"
              :disabled="!isNavTextHidden"
            >
              <router-link
                :to="item.path"
                class="nav-item"
                :class="{ active: $route.path === item.path }"
              >
                <el-icon class="nav-icon">
                  <component :is="item.icon" />
                </el-icon>
                <span class="nav-text">{{ t(item.title) }}</span>
              </router-link>
            </el-tooltip>
          </div>
        </div>

        <div class="nav-section">
          <!-- <span class="nav-section-title">{{ t('dashboard.layout.sidebar.collaboration') }}</span> -->
          <div class="nav-items">
            <el-tooltip
              v-for="item in collaborationMenus"
              :key="item.path"
              :content="t(item.title)"
              placement="bottom"
              :show-after="500"
              :disabled="!isNavTextHidden"
            >
              <router-link
                :to="item.path"
                class="nav-item"
                :class="{ active: $route.path === item.path }"
              >
                <el-icon class="nav-icon">
                  <component :is="item.icon" />
                </el-icon>
                <span class="nav-text">{{ t(item.title) }}</span>
              </router-link>
            </el-tooltip>
          </div>
        </div>

        <div class="nav-section">
          <!-- <span class="nav-section-title">{{ t('dashboard.layout.sidebar.aiFeatures') }}</span> -->
          <div class="nav-items">
            <el-tooltip
              v-for="item in aiMenus"
              :key="item.path"
              :content="t(item.title)"
              placement="bottom"
              :show-after="500"
              :disabled="!isNavTextHidden"
            >
              <router-link
                :to="item.path"
                class="nav-item"
                :class="{ active: $route.path.startsWith(item.path) }"
              >
                <el-icon class="nav-icon">
                  <component :is="item.icon" />
                </el-icon>
                <span class="nav-text">{{ t(item.title) }}</span>
              </router-link>
            </el-tooltip>
          </div>
        </div>
        <div class="nav-section">
          <div class="nav-items">
            <el-tooltip
              v-for="item in vipMenus"
              :key="item.path"
              :content="t(item.title)"
              placement="bottom"
              :show-after="500"
              :disabled="!isNavTextHidden"
            >
              <router-link
                :to="item.path"
                class="nav-item vip-nav-item"
                :class="{ active: $route.path === item.path }"
              >
                <el-icon class="nav-icon">
                  <component :is="item.icon" />
                </el-icon>
                <span class="nav-text">{{ t(item.title) }}</span>
              </router-link>
            </el-tooltip>
          </div>
        </div>

<div class="nav-section" v-if="authStore.isAdmin">
          <span class="nav-section-title">{{ t('dashboard.layout.sidebar.admin') }}</span>
          <div class="nav-items">
            <el-tooltip
              v-for="item in adminMenus"
              :key="item.path"
              :content="t(item.title)"
              placement="bottom"
              :show-after="500"
              :disabled="!isNavTextHidden"
            >
              <!-- 普通管理员菜单 -->
              <router-link
                v-if="!item.requiresDeveloperAuth"
                :to="item.path"
                class="nav-item"
                :class="{ active: $route.path === item.path }"
              >
                <el-icon class="nav-icon">
                  <component :is="item.icon" />
                </el-icon>
                <span class="nav-text">{{ t(item.title) }}</span>
              </router-link>

              <!-- 需要开发者认证的菜单 -->
              <div
                v-else
                class="nav-item developer-item"
                :class="{ active: $route.path === item.path }"
                @click="handleDeveloperMenuClick(item)"
              >
                <el-icon class="nav-icon">
                  <component :is="item.icon" />
                </el-icon>
                <span class="nav-text">{{ t(item.title) }}</span>
                <el-icon class="developer-lock">
                  <Lock />
                </el-icon>
              </div>
            </el-tooltip>
          </div>
        </div>
   
        
      </div>
    </nav>

    <!-- 主内容区 -->
    <main class="dashboard-main">
      <div class="dashboard-content">
        <router-view />
      </div>
    </main>

    <!-- 开发者认证组件 -->
    <DeveloperAuth
      ref="developerAuthRef"
      v-model="showDeveloperAuth"
      @success="onDeveloperAuthSuccess"
      @cancel="onDeveloperAuthCancel"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Folder, Search, User, Setting, SwitchButton, ArrowDown, Sunny, Moon, UserFilled, Link, Medal, Lock
} from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { useThemeStore } from '@/stores/theme'
import GlobalSearch from '@/components/common/GlobalSearch.vue'
import TitleBar from '@/components/electron/TitleBar.vue'
import DeveloperAuth from '@/components/developer/DeveloperAuth.vue'

const router = useRouter()
const authStore = useAuthStore()
const themeStore = useThemeStore()
const { t } = useI18n()

// 检测是否为Electron环境
const isElectron = !!(window as any).electronAPI

// 响应式检测：判断是否隐藏导航文字
const isNavTextHidden = ref(false)

// 开发者认证相关
const showDeveloperAuth = ref(false)
const pendingDeveloperRoute = ref<any>(null)
const developerAuthRef = ref<InstanceType<typeof DeveloperAuth> | null>(null)

const checkScreenSize = () => {
  isNavTextHidden.value = window.innerWidth <= 1200
}

onMounted(() => {
  checkScreenSize()
  window.addEventListener('resize', checkScreenSize)
})

onUnmounted(() => {
  window.removeEventListener('resize', checkScreenSize)
})

// 菜单配置
const fileMenus = [
  { path: '/dashboard', title: 'dashboard.layout.sidebar.menus.home', icon: 'HomeFilled' },
  { path: '/dashboard/files', title: 'dashboard.layout.sidebar.menus.myFiles', icon: 'Files' },
  { path: '/dashboard/transfer', title: 'dashboard.layout.sidebar.menus.transfer', icon: 'Upload' },
  { path: '/dashboard/shared', title: 'dashboard.layout.sidebar.menus.shared', icon: 'Share' },
  { path: '/dashboard/favorites', title: 'dashboard.layout.sidebar.menus.favorites', icon: 'Star' },
  { path: '/dashboard/trash', title: 'dashboard.layout.sidebar.menus.trash', icon: 'Delete' }
]

const aiMenus = [
  { path: '/dashboard/ai-chat', title: 'dashboard.layout.sidebar.menus.aiChat', icon: 'ChatDotRound' },
  { path: '/dashboard/work-reports', title: 'dashboard.layout.sidebar.menus.workReports', icon: 'Document' }
]

const collaborationMenus = [
  { path: '/dashboard/contacts', title: 'dashboard.layout.sidebar.menus.contacts', icon: 'User' },
  { path: '/dashboard/team', title: 'dashboard.layout.sidebar.menus.teams', icon: 'UserFilled' }
]

const vipMenus = [
  { path: '/dashboard/vip-center', title: 'dashboard.layout.sidebar.menus.vipCenter', icon: 'Medal' }
]

const adminMenus = [
   { path: '/dashboard/admin/team-approval', title: 'dashboard.layout.sidebar.menus.teamApproval', icon: 'UserFilled', requiresDeveloperAuth: false },
  { path: '/dashboard/test/rabbitmq', title: 'dashboard.layout.sidebar.menus.rabbitmqTest', icon: 'Link', requiresDeveloperAuth: true }
]

// 存储空间计算
const storagePercentage = computed(() => {
  const used = authStore.user?.storageUsed || 0
  const quota = authStore.user?.storageQuota || 1
  return Math.round((used / quota) * 100)
})

const storageColor = computed(() => {
  const percentage = storagePercentage.value
  if (percentage >= 90) return '#f56c6c'
  if (percentage >= 70) return '#e6a23c'
  return '#67c23a'
})

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 主题切换
const toggleTheme = () => {
  themeStore.toggleTheme()
}

// 用户菜单处理
const handleUserCommand = async (command: string) => {
  switch (command) {
    case 'vip':
      router.push('/dashboard/vip-center')
      break
    case 'profile':
      router.push('/dashboard/profile')
      break
    case 'settings':
      router.push('/dashboard/settings')
      break
    case 'logout':
      try {
        await ElMessageBox.confirm(
          t('dashboard.layout.logoutConfirm.text'),
          t('dashboard.layout.logoutConfirm.title'),
          {
            confirmButtonText: t('dashboard.layout.logoutConfirm.confirmButton'),
            cancelButtonText: t('dashboard.layout.logoutConfirm.cancelButton'),
            type: 'warning'
          }
        )
        await authStore.logout()
      } catch (error) {
        // 用户取消
      }
      break
  }
}

// 处理开发者菜单点击
const handleDeveloperMenuClick = (menuItem: any) => {
  // 检查是否已经认证
  if (developerAuthRef.value?.checkAuthenticated()) {
    // 已认证，直接跳转
    router.push(menuItem.path)
  } else {
    // 未认证，显示认证对话框
    pendingDeveloperRoute.value = menuItem
    showDeveloperAuth.value = true
  }
}

// 开发者认证成功回调
const onDeveloperAuthSuccess = (sessionToken: string) => {
  if (pendingDeveloperRoute.value) {
    // 跳转到目标页面
    router.push(pendingDeveloperRoute.value.path)
    pendingDeveloperRoute.value = null
  }
}

// 开发者认证取消回调
const onDeveloperAuthCancel = () => {
  pendingDeveloperRoute.value = null
}
</script>

<style lang="scss" scoped>
.dashboard-container.horizontal-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.dashboard-header {
  height: 60px;
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);

  .header-left {
    display: flex;
    align-items: center;
    gap: 24px;

    .logo {
      display: flex;
      align-items: center;
      gap: 8px;

      .logo-icon {
        font-size: 24px;
        color: var(--el-color-primary);
      }

      .logo-text {
        font-size: 18px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }
    }
  }

  .header-right {
    display: flex;
    align-items: center;
    gap: 16px;

    .storage-info-horizontal {
      display: flex;
      flex-direction: column;
      gap: 4px;
      min-width: 140px;

      .storage-text {
        display: flex;
        flex-direction: column;
        align-items: flex-end;

        .storage-label {
          font-size: 11px;
          font-weight: 600;
          color: var(--el-text-color-secondary);
          text-transform: uppercase;
          letter-spacing: 0.5px;
        }

        .storage-usage {
          font-size: 12px;
          color: var(--el-text-color-primary);
          font-weight: 500;
        }
      }

      .storage-progress {
        :deep(.el-progress-bar) {
          .el-progress-bar__outer {
            border-radius: 3px;
          }
        }
      }
    }

    .theme-toggle-btn {
      width: 36px;
      height: 36px;
      border-radius: 50%;
      transition: all 0.3s ease;

      &:hover {
        background-color: var(--el-fill-color-light);
        transform: scale(1.1);
      }

      .el-icon {
        font-size: 18px;
        color: var(--el-text-color-primary);
      }
    }

    .user-info {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 8px 12px;
      border-radius: 6px;
      cursor: pointer;
      transition: background-color 0.2s;

      &:hover {
        background: var(--el-fill-color-light);
      }

      .username {
        font-size: 14px;
        color: var(--el-text-color-primary);
      }
    }
  }
}

.horizontal-nav {
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color);
  padding: 6px 10px;
  overflow-x: auto;
  overflow-y: hidden;

  // 美化滚动条
  &::-webkit-scrollbar {
    height: 6px;
  }

  &::-webkit-scrollbar-track {
    background: transparent;
  }

  &::-webkit-scrollbar-thumb {
    background: var(--el-border-color-light);
    border-radius: 3px;

    &:hover {
      background: var(--el-border-color);
    }
  }

  .nav-container {
    display: flex;
    gap: 19px;
    align-items: center;
    min-width: max-content;

    .nav-section {
      display: flex;
      align-items: center;
      gap: 10px;

      .nav-section-title {
        font-size: 12px;
        font-weight: 600;
        color: var(--el-text-color-secondary);
        text-transform: uppercase;
        letter-spacing: 0.5px;
        white-space: nowrap;
      }

      .nav-items {
        display: flex;
        gap: 8px;

        .nav-item {
          display: flex;
          align-items: center;
          gap: 6px;
          padding: 8px 12px;
          color: var(--el-text-color-regular);
          text-decoration: none;
          border-radius: 6px;
          transition: all 0.2s;
          white-space: nowrap;

          &:hover {
            background: var(--el-fill-color-light);
            color: var(--el-text-color-primary);
          }

          &.active {
            background: var(--el-color-primary-light-9);
            color: var(--el-color-primary);
          }

          .nav-icon {
            font-size: 14px;
          }

          .nav-text {
            font-size: 13px;
          }

          // VIP菜单特殊样式
          &.vip-nav-item {
            position: relative;
            background: var(--el-color-warning-light-8);
            border: 1px solid #f39c12;
            border-radius: 6px;

            .nav-icon {
              color: #f39c12;
            }

            &:hover {
              background: var(--el-color-warning-light-7);
              border-color: #e67e22;

              .nav-icon {
                color: #e67e22;
              }
            }

            &.active {
              background: var(--el-color-warning-light-8);
              color: #f39c12;

              .nav-icon {
                color: #f39c12;
              }
            }
          }

          // 开发者菜单特殊样式
          &.developer-item {
            cursor: pointer;
            position: relative;

            .developer-lock {
              font-size: 12px;
              color: #e6a23c;
              margin-left: 4px;
            }

            &:hover {
              background: #fff7e6;
              color: #cf9236;

              .developer-lock {
                color: #cf9236;
              }
            }
          }
        }
      }
    }
  }
}

// VIP下拉菜单项样式
:deep(.vip-menu-item) {
  .el-icon {
    color: #f39c12;
  }

  &:hover {
    background: var(--el-color-warning-light-8);
  }
}

.dashboard-main {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  .dashboard-content {
    flex: 1;
    overflow: auto;
    background: var(--el-bg-color-page);
  }
}

@media (max-width: 1200px) {
  .dashboard-header {
    .header-right {
      .storage-info-horizontal {
        min-width: 120px;

        .storage-text {
          .storage-usage {
            font-size: 11px;
          }
        }
      }
    }
  }

  .horizontal-nav {
    .nav-container {
      gap: 32px;

      .nav-section {
        .nav-items {
          .nav-item {
            .nav-text {
              display: none;
            }
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .dashboard-header {
    padding: 0 16px;

    .header-left {
      gap: 16px;
    }

    .header-right {
      gap: 12px;

      .storage-info-horizontal {
        min-width: 120px;

        .storage-text {
          .storage-usage {
            font-size: 11px;
          }
        }
      }
    }
  }

  .horizontal-nav {
    padding: 8px 16px;
    overflow-x: auto;

    .nav-container {
      gap: 24px;
      min-width: max-content;

      .nav-section {
        .nav-section-title {
          display: none;
        }
      }
    }
  }
}


</style>
